package com.yanqu.road.server.cmd.activity.peakstronghold;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.peakstronghold.config.PeakStrongHoldConfig;
import com.yanqu.road.entity.activity.peakstronghold.config.ePeakStrongholdStageType;
import com.yanqu.road.entity.activity.stronghold.StrongholdMammonInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.PeakStrongholdWarProto;
import com.yanqu.road.pb.activity.StrongholdWarProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.peakstronghold.PeakStrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdActivityMgr;
import com.yanqu.road.server.manger.activity.strongholdwar.StrongholdWarMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.system.CommonMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;

@Cmd(code = GameProtocol.S_PEAK_STRONGHOLD_ELIMINATION_MAMMON_HELP,desc = "财神助力")
public class PeakStrongholdMammonHelpCmd extends AbstractCommand {
    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {

        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        PeakStrongHoldConfig config = PeakStrongholdActivityMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            ret = GameErrorCode.E_ACTIVITY_NO_FOUND;
            return;
        }

        if (!PeakStrongholdActivityMgr.canUnionInBattle(player.getUserInfo().getUnionUid())) {
            ret = GameErrorCode.E_PEAK_HOLD_NOT_IN_ELIMINATE;
            return;
        }
        if (config.getStageType() != ePeakStrongholdStageType.InBattle) {
            ret = GameErrorCode.E_PEAK_HOLD_ELIMINATE_NOT_BEGIN;
            return;
        }
        int activityId = config.getActivityInfo().getActivityId();
        PeakStrongholdWarProto.PeakMammonHelpReqMsg req = PeakStrongholdWarProto.PeakMammonHelpReqMsg.parseFrom(packet.getBytes());
        int type = req.getType();

        String unionUid = player.getUserInfo().getUnionUid();
        String mammonConsume = config.getMammonHelpConsume();

        if (req.getType() == 1) {
            //指定商会
            if (!req.hasUnionId() || StringUtils.isNullOrEmpty(req.getUnionId())) {
                ret = GameErrorCode.E_STRONGHOLD_MAMMON_HELP_NO_APPOINT_UNION;
                return;
            }
        }

        ret = checkCanUseMammonHelp(player, config, unionUid, mammonConsume);
        if (ret != 0) {
            return;
        }

        Property property = PropertyHelper.parseStringToProperty(mammonConsume);
        GoodsInfo goodsInfo = null;
        for (Integer goodsId : property.getGoods().keySet()) {
            goodsInfo = CommonMgr.getGoodsInfo(goodsId);
        }

        int effectType = config.getMammonHelpEffectType();
        //伤害效果
        UserPatrons patrons = PatronsMgr.getUserPatronsByEarnSpeedRank(1,player.getModule(PatronsModule.class).getUserPatronsList());
        StrongholdMammonInfo mammonInfo = calcDamage(type, goodsInfo.getExtendParam(), patrons.getAbility());
        PeakStrongholdWarProto.CrossPeakStrongholdMammonHelpReqMsg.Builder crossMsg = PeakStrongholdWarProto.CrossPeakStrongholdMammonHelpReqMsg.newBuilder();
        crossMsg.setActivityId(activityId);
        crossMsg.setType(effectType);
        if (req.hasUnionId()) {
            crossMsg.setUnionId(req.getUnionId());
        }
        crossMsg.setDamage(mammonInfo.getTotalDamage().toString());
        crossMsg.setAttackTimes(mammonInfo.getAttackTimes());
        crossMsg.setUserBaseInfo(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
        crossMsg.setGoodsId(goodsInfo.getGoodsId());
        crossMsg.setMammonType(type);
        String ownUnionUid = GameUnionActivityGroupMgr.getUnionUid(crossMsg.getActivityId(), player.getUserId());
        crossMsg.setOwnUnionId(ownUnionUid);
        player.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_ELIMINATION_MAMMON_HELP, crossMsg, crossMsg.getActivityId());
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret != 0) {
            PeakStrongholdWarProto.PeakMammonHelpRespMsg.Builder resp = PeakStrongholdWarProto.PeakMammonHelpRespMsg.newBuilder();
            resp.setRet(ret);
            player.sendPacket(ClientProtocol.U_PEAK_STRONGHOLD_ELIMINATION_MAMMON_HELP, resp);
        }
    }

    private int  checkCanUseMammonHelp(GamePlayer player, PeakStrongHoldConfig config, String unionUid, String mammonConsume) {
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        if (!PeakStrongholdActivityMgr.canUnionInBattle(player.getUserInfo().getUnionUid())) {
            return GameErrorCode.E_PEAK_HOLD_NOT_IN_ELIMINATE;
        }
        if (config.getStageType() != ePeakStrongholdStageType.InBattle) {
            return GameErrorCode.E_STRONGHOLD_ELIMINATE_NO_OPEN;
        }
        boolean hasQualification = PeakStrongholdActivityMgr.canUnionInBattle(unionUid);
        if (!hasQualification) {
            return GameErrorCode.E_STRONGHOLD_NO_QUALIFICATION;
        }
        if (mammonConsume == null) {
            return GameErrorCode.E_BAG_ITEM_NO_EXIST;
        }
        Property property = PropertyHelper.parseStringToProperty(mammonConsume);
        GoodsInfo goodsInfo = null;
        for (Integer goodsId : property.getGoods().keySet()) {
            goodsInfo = CommonMgr.getGoodsInfo(goodsId);
        }
        if (goodsInfo == null) {
            return GameErrorCode.E_BAG_ITEM_NO_EXIST;
        }
        if (!player.getModule(CurrencyModule.class).currencyIsEnough(property)) {
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }

        //预扣
        player.getModule(PreReduceModule.class).preReduce(property);
        return 0;
    }

    private StrongholdMammonInfo calcDamage(int type, String paramStr, BigInteger patronsAbility) {
        String s = paramStr.split("-")[type - 1];
        String[] arr = s.split("\\|");
        if (type == 1) {
            BigInteger totalDamage = new BigDecimal(patronsAbility).add(new BigDecimal(arr[3]))
                    .multiply(new BigDecimal(arr[0])).multiply(new BigDecimal(arr[1])).divide(new BigDecimal("1000"),2,BigDecimal.ROUND_HALF_UP).toBigInteger();
            return new StrongholdMammonInfo(totalDamage, 1);
        }else {
            BigInteger totalDamage = new BigDecimal(patronsAbility).add(new BigDecimal(arr[3])).multiply(new BigDecimal(arr[1])).divide(new BigDecimal("1000"),2,BigDecimal.ROUND_HALF_UP).toBigInteger();
            int attckTimes = Integer.parseInt(arr[0]);
            return new StrongholdMammonInfo(totalDamage, attckTimes);
        }
    }
}
